#-*- coding:utf-8 -*-
from pymongo.database import ObjectId
from bottle import HTTPError

class Args():
    def __init__(self,args):
        self.args = {}
        for k in args.dict:
            vals = args.dict[k]
            if len(vals) > 0:
                self.args[k] = vals[0]
        self.err = None

    def setError(self, msg):
        if not self.err:
            self.err = HTTPError(400, msg)
        else:
            self.err.body += ',' + msg

    def __getattr__(self, name):
        if name in ('err'):
            return self.__getattr__(name)
        elif self.args.has_key(name):
            return self.args[name]
        else:
            return None

    #获取某属性的值，带默认值参数
    def getVal(self,name,default=''):
        if self.args.has_key(name):
            return self.args[name]
        else:
            return default

    def isEmpty(self,name):
        empty = not self.args.has_key(name)
        empty = empty or self.args[name].lstrip() == ''
        return empty 

    #必填参数校验
    def require(self,*names):
        for name in names:
            val = None
            if self.args.has_key(name):
                val = self.args[name]
                if (not val) or (val.lstrip() == ''):
                    val = None
                    del self.args[name]
            if not val:
                self.setError('参数%s不能为空' % (name))
                
        return self

    #mongo ObjectId校验
    def isObjectId(self,name):
        if self.isEmpty(name):
            return self

        val = self.args[name]
        if not ObjectId.is_valid(val):
            self.setError('参数%s格式不正确' % (name))
        return self
            
    def isObjectIds(self, name):
        if self.isEmpty(name):
            return self

        val = self.args[name]
        vals = val.split(',')
        for objctId in vals:
            if not ObjectId.is_valid(val):
                self.setError('参数%s格式不正确' % (name))
                break        
        return self

    #浮点数校验
    def isFloat(self,name):
        if self.isEmpty(name):
            return self

        val = self.args[name]
        print val
        try:
            val = float(val)
            self.args[name] = val
        except TypeError, e:
            self.setError('参数%s必须是浮点数' % (name))

        return self

    #整数校验
    def isInt(self,name):
        if self.isEmpty(name):
            return self

        val = self.args[name]
        try:
            val = int(val)
            self.args[name] = val
        except err:
            self.setError('参数%s必须是整数' % (name))

        return self